`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date: 2023/09/19 20:47:25
// Design Name: 
// Module Name: sampling
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////

/* 循环采样 */

module sampling(
    input clk, 
    input [23:0] led, 
    input [7:0] bit_sel,
    input [7:0] seg_sel,
    input tx_done,              // 串口发送完毕的信号
    input turn_start,           // 轮开始信号 编码为 0x9d

    output reg txd_start,       // 串口发送信号
    output reg [7:0] tx_data    // 串口并行数据
    );

    parameter TURN = 5; // 每轮发送 5 byte

    // 暂时存储当前轮次的信号状态
    reg [23:0] tmp_led;
    reg [7:0] tmp_bs;
    reg [7:0] tmp_ss;

    reg [3:0] no_cnt = 4'd0;    // 采样个数计数器 0 ~ 4
    reg turn_en;                // 轮使能信号
    reg [1:0] tx_done_r;        // 边沿检测

    always @ (posedge clk) begin
        tx_done_r <= {tx_done_r[0], tx_done};
    end

    // 当 turn_start 拉高时，开始一轮的采样和发送
    always @ (posedge clk) begin
        if (turn_start || (turn_en && (tx_done_r == 2'b10)))
            txd_start <= 1'b1;
        else 
            txd_start <= 1'b0; 
    end

    // 设置使能信号，只有使能信号为高时，计数器才工作
    always @ (posedge clk) begin
        if (turn_start) 
            turn_en <= 1'b1;
        else if ((no_cnt == TURN - 1) && (tx_done))
            turn_en <= 1'b0;
        else 
            turn_en <= turn_en;
    end

    always @ (posedge clk) begin
        if (turn_en) begin
            if ((no_cnt == TURN - 1) && (tx_done))
                no_cnt <= 4'd0;
            else if (tx_done)
                no_cnt <= no_cnt + 1'b1;
            else 
                no_cnt <= no_cnt;
        end
        else 
            no_cnt <= 4'd0;
    end

    always @(posedge clk) begin
        if (no_cnt == 4'd0) begin
            tmp_led <= led;
            tmp_bs <= bit_sel;
            tmp_ss <= seg_sel;
        end
        else begin
            tmp_led <= tmp_led;
            tmp_bs <= tmp_bs;
            tmp_ss <= tmp_ss;
        end
    end

    always @ (posedge clk) begin
        case (no_cnt) 
            4'd0: tx_data <= tmp_led[7:0];
            4'd1: tx_data <= tmp_led[15:8];
            4'd2: tx_data <= tmp_led[23:16];
            4'd3: tx_data <= tmp_bs;
            4'd4: tx_data <= tmp_ss;
        endcase
    end


endmodule
